var express = require("express");
var router = express.Router();
const Db = require("../utils/db");
const createSql = require("../utils/Create_SQL");
const path = require('path');
const fs = require('fs');
const {errorCode , successCode , config} = require('../config/config');
let request = require("request");
const utils = require("../utils/utils.js");


/**
 * @swagger
 * /api/weixin/getUnlimitedQRCode:
 *    post:
 *      tags:
 *      - 微信相关
 *      summary: 生成小程序 太阳码
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                data:
 *                  type: string
 *                  required: true
 *                  description: 需要请求的参数 
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/getUnlimitedQRCode" , async (req , res )=>{
    // 需要请求的参数 {data : code=1683170010639&admin=true}
    const {data} = req.body;
    let access_token = await utils.getAccessToken();
    console.log("access_token ==>" ,access_token);
    let url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}`;
    request.post({
        url : url ,
        body : JSON.stringify({
            "scene" : data,
            "page" : "pages/authorization/authorization",
            "check_path": true,
            "env_version" : "release",  // develop 开发 trial 体验 release正式
        }),
        encoding: "base64" 
    },(error, response, body) => {
        return res.json({
            code : 200,
            msg : "获取成功",
            body : "data:image/png;base64," + body
        })
    })
})

/**
 * @swagger
 * /api/weinxin/getOpenid:
 *    post:
 *      tags:
 *      - 微信相关
 *      summary: 获取用户openid
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                code:
 *                  type: string
 *                  required: true
 *                  description: 微信登录的code
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/getOpenid" , async (req , res )=>{
    const {code} = req.body;
    if(!code){
        return res.json(errorCode["10003"])
    }
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.appid}&secret=${config.AppSecret}&js_code=${code}&grant_type=authorization_code`;
    request.get(url , (error , response , body)=>{
        return res.json({
            code : 200,
            msg : "获取成功",
            data : JSON.parse(body)
        })
    })
})

/**
 * @swagger
 * /api/weinxin/wxLogin:
 *    post:
 *      tags:
 *      - 微信相关
 *      summary: 微信一键登录
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                openid:
 *                  type: string
 *                  required: true
 *                  description: 登录的openid
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/wxLogin" , async (req , res )=>{
    const {openid} = req.body;
    if(!openid){
        return res.json(errorCode["10003"])
    }
    let sql = createSql.select().from("web_userinfo").where(`openid = '${openid}'`).end();
    let reslut = await Db.query(sql , res);
    if(reslut.code > 200) return;
    if(reslut.length > 0){
        handleLoginSuccess(reslut[0] , req , res);
        return ;
    }
    sql = createSql.insert("web_userinfo").value({
        ID: utils.getUuid(),
        icon : '/img/user-icon.png',
        username: 'zsduan' + new Date().getTime(),
        password: utils.MD5({ word: '123456' }),
        addtime: utils.getTime(),
        openid : openid
    }).end();
    reslut = await Db.query(sql , res);
    if(reslut.code > 200) return;
    sql = createSql.select().from("web_userinfo").where(`openid = '${openid}'`).end();
    reslut = await Db.query(sql , res);
    if(reslut.code > 200) return;
    handleLoginSuccess(reslut[0] , req , res);
})

/**处理登录成功后 -用户*/
const handleLoginSuccess = async (data, req, res) => {
    let ip = utils.getClientIP(req);
    if (data.is_stop != '0') {
        res.status(500);
        return res.json({
            ...errorCode[10010],
            message: "该用户已被禁用"
        })
    }
    res.clearCookie('token');
    let tokenJson = {
        ID: data.ID,
        username: data.username,
        password: data.password,
    }
    let token = utils.GenerateSecretKey(tokenJson, config.secretOrPrivateKey);
    sql = createSql.update("web_userinfo").set({ loginIP: ip, ua : JSON.stringify({ua : "微信小程序"}) , lastLoginTime: utils.getTime("yyyy-MM-dd HH:mm:ss") }).where(`ID = '${data.ID}'`).end();
    let reslut = await Db.query(sql, res);
    if (reslut.code > 200) {
        return;
    }
    if(data.icon.indexOf("http") == -1 && data.icon.indexOf('wxfile') == -1){
        data.icon = config.httpImgUrl + data.icon;
    }
    res.cookie('token', token, { maxAge: 1000 * 60 * 60 * 24 * 1, httpOnly: true });
    delete data.password;
    return res.json({
        ...successCode[200],
        token: token,
        data: {
            ...data,
            fistPassWord : "123456"
        } ,
        message : "登录成功"
    })
}
 
/**
 * @swagger
 * /api/weixin/messageSubscribeSend:
 *    get:
 *      tags:
 *      - 微信相关
 *      summary: 发送订阅消息
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: ID
 *          description: 文章id
 *          in: query
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/messageSubscribeSend" , async (req , res )=>{
    const query = req.query;
    if(!query.ID){
        return res.json(errorCode["10003"])
    }
    let sql  = createSql.select().from("article_view").where(`ID = '${query.ID}'`).build();
    let reslut = await Db.query(sql , res);
    if(reslut.code > 200) return;
    reslut = utils.formatDateByArray(reslut , ["addtime" , 'updatetime'])
    let data = reslut[0];
    let sendData = {
        thing1 : {
            value : data.title
        },
        time2 : {
            value : data.updatetime || data.addtime
        },
        name4 : {
            value : data.createByUser
        },
        thing5 : {
            value : '新的文章发布了，快来看看吧'
        }
    }
    let access_token = await utils.getAccessToken();
    request(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`, {
        json : true,
        headers : {
            'Content-Type': 'application/json'
        },
        method : "POST",
        body : {
            touser : "onMl45Homj0Hzv3lWlSpHaVYFMoc",
            template_id : "JPJWxKu4XJIRvAXMDIN7-Il3nrbnZEe6Gof-7ksTu_Y",
            page : `pages/details/details?id=${query.ID}`,
            data : sendData
        }
    },(err , response , body)=>{
        if(err){
            res.json({
                code : 500,
                msg : "获取失败",
                data : err
            })
            return;
        }
        res.json({
            code : 200,
            msg : "获取成功",
            data : body
        })
    })
})

module.exports = router;